import { createRouter, createWebHistory } from "vue-router";
import Layout from "../layout/Index.vue";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false });

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/login",
      name: "login",
      meta: { title: "登录", name: "login" },
      component: () => import("../pages/login/Login.vue"),
    },
    {
      path: "",
      name: "Layout",
      component: Layout,
      // 自定义属性，设置是否必须Authorization
      meta: {
        requireAuth: true,
      },
      children: [
        {
          path: "/info",
          name: "info",
          meta: { title: "个人中心", name: "/info" },
          component: () => import("../pages/common/Info.vue"),
        },
        {
          path: "/error",
          name: "NotFound",
          meta: { title: "404", name: "404" },
          component: () => import("../components/NotFound.vue"),
        },
        {
          path: "/:w+",
          redirect: { name: "NotFound" },
        },
        {
          path: "/user",
          name: "user",
          meta: { title: "用户列表", name: "/user" },
          component: () => import("../pages/manager/UserList.vue"),
        },
        {
          path: "/grpc",
          name: "grpc",
          meta: { title: "消息接收", name: "/grpc" },
          component: () => import("../pages/manager/Grpc.vue"),
        },
      ],
    },
  ],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

router.beforeEach((to, from, next) => {
  NProgress.start();
  if (to.meta.title) {
    document.title = to.meta.title;
  }

  // 根据设置的requireAuth客户端简单验证token是否存在
  if (to.matched.some((r) => r.meta.requireAuth)) {
    let token = sessionStorage.getItem("Authorization");
    if (token) {
      next();
    } else {
      next("/login");
    }
  } else {
    next();
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
